package com.mz.ozy.activity.find;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mz.ozy.R;
import com.mz.ozy.activity.c2c.PhotoScanActivity;
import com.mz.ozy.adapter.ReplyListAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.DynamicsDetailBean;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.ReplyBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.model.FollowModel;
import com.mz.ozy.mvp.presenter.DynamicsDetailPresenter;
import com.mz.ozy.mvp.view.DynamicsDetailContract;
import com.mz.ozy.utils.CalendarUtils;
import com.mz.ozy.utils.EmojiUtils;
import com.mz.ozy.utils.KeyboardChangeListener;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.FriendsCircleImageLayout;
import com.mz.ozy.widget.dialog.BaseDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.mz.ozy.utils.KeyboardChangeListener.KeyBoardListener;

public class DynamicDetailActivity extends BaseActivity<DynamicsDetailContract.View, DynamicsDetailPresenter> implements DynamicsDetailContract.View, KeyBoardListener {
    public static final String DYNAMICS_ID = "DYNAMICS_ID";
    public static final String DYNAMICS_UID = "DYNAMICS_UID";
    public static final String DYNAMICS_CID = "DYNAMICS_CID";

    @BindView(R.id.iv_dynamics_user_head)
    ImageView mIvDynamicsUserHead;
    @BindView(R.id.tv_dynamics_user_name)
    TextView mTvDynamicsUserName;

    @BindView(R.id.tv_dynamics_time)
    TextView mTvDynamicsTime;
    @BindView(R.id.tv_friend_dynamics_content)
    TextView mTvDynamicsContent;
    @BindView(R.id.tv_friend_dynamics_commentnum)
    TextView mTvCommentNum;
    @BindView(R.id.tv_friend_dynamics_address)
    TextView mTvAddress;
    @BindView(R.id.tv_friend_dynamics_deletes)
    TextView mTvDelete;
    @BindView(R.id.fcil_friend_dynamics_imgs)
    FriendsCircleImageLayout mFriendsCircleImageLayout;

    @BindView(R.id.et_dynamics_comment_input)
    EditText mEtCommentInput;
    //    @BindView(R.id.et_dynamics_comment)
//    EditText mEtComment;
//    @BindView(R.id.iv_comment_send)
//    ImageView mIvCommentSend;
//    @BindView(R.id.rl_dynamics_comment)
//    RelativeLayout mRlDynamicsComment;
    @BindView(R.id.rv_friend_comments)
    RecyclerView mRvFriendComments;
    @BindView(R.id.rl_friend_comments)
    RelativeLayout mRlFriendComments;
    @BindView(R.id.srl_refresh)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.iv_friend_dynamics_like)
    ImageView mIvFriendDynamicsLike;
    @BindView(R.id.tv_friend_dynamics_likenum)
    TextView mTvFriendDynamicsLikenum;
    @BindView(R.id.iv_friend_dynamics_location)
    ImageView mIvFriendDynamicsLocation;
    @BindView(R.id.ll_friend_dynamics_comment)
    LinearLayout mLlDynamicsComment;
    @BindView(R.id.ll_friend_dynamics_like)
    LinearLayout mLlDynamicsLike;
    @BindView(R.id.ll_send_comment)
    LinearLayout mLlSendComment;
    @BindView(R.id.tv_comment_send)
    TextView mTvSendComment;
    @BindView(R.id.tv_dynamic_topic)
    TextView mTvDynamicTopic;

    private KeyboardChangeListener mKeyboardChangeListener;

    private Unbinder unbinder;
    private int mDynamicsID;
    private String mUid;
    private String mCid;

    private ReplyListAdapter commentReplyAdapter;

    private String mHostName;
    private InputMethodManager manager;
    private ReplyBean mCurReply;
    private DynamicsDetailBean.DynamicsDetail dynamicsDetail;
    private int isZan = 0;
    private int zanNum = 0;
    private long curTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_detail);
        unbinder = ButterKnife.bind(this);
        initTitle3();
        tvTitle.setVisibility(View.GONE);
        tvCenterTitle.setText("动态详情");

        initData();
        initView();
        initKeyBoardListener();
        initRefreshLayout();
        initEvents();
        mPresenter.queryDynamicsDetail(DynamicDetailActivity.this, mDynamicsID);
    }

    private void initEvents() {
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEtCommentInput.requestFocus();
                manager.hideSoftInputFromWindow(mEtCommentInput.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
                finish();
            }
        });
        mTvSendComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (sendComment()) {
                    return;
                }
                if (manager != null) {
                    manager.hideSoftInputFromWindow(mEtCommentInput.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
                    mEtCommentInput.clearFocus();
                }
            }
        });

        mEtCommentInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    if (sendComment()) {
                        return false;
                    }

                    if (manager != null) {
                        manager.hideSoftInputFromWindow(textView.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
                        mEtCommentInput.clearFocus();
                    }
                    return true;
                }
                return false;
            }
        });

        mEtCommentInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (manager != null)
                        manager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
                }
            }
        });

        commentReplyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                final ReplyBean replyBean = commentReplyAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.tv_reply_name: {
                        if (!TextUtils.isEmpty(mUid) && mUid.equals(replyBean.getUid() + "")) {
                            finish();
                        } else {
                            Intent intent = new Intent(DynamicDetailActivity.this, HomePageActivity.class);
                            intent.putExtra("id", replyBean.getUid() + "");
                            startActivity(intent);
                        }
                        break;
                    }
                    case R.id.tv_host_name: {
                        if (!TextUtils.isEmpty(mUid) && mUid.equals(replyBean.getUuid())) {
                            finish();
                        } else {
                            Intent intent = new Intent(DynamicDetailActivity.this, HomePageActivity.class);
                            intent.putExtra("id", replyBean.getUuid());
                            startActivity(intent);
                        }
                        break;
                    }
                    case R.id.tv_reply_label:
                    case R.id.tv_reply_content: {
                        mCurReply = commentReplyAdapter.getItem(position);
                        mHostName = mCurReply.getUname();
                        mEtCommentInput.setHint("@" + mHostName);
                        mLlSendComment.setVisibility(View.VISIBLE);
                        mEtCommentInput.requestFocus();
                        if (manager != null)
                            manager.showSoftInput(mEtCommentInput, InputMethodManager.SHOW_IMPLICIT);
                        break;
                    }
                }
            }
        });

        mLlDynamicsComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mLlSendComment.setVisibility(View.VISIBLE);
                mEtCommentInput.requestFocus();
                if (manager != null)
                    manager.showSoftInput(mEtCommentInput, InputMethodManager.SHOW_IMPLICIT);
            }
        });

        mLlDynamicsLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (dynamicsDetail != null) {
                    mPresenter.followDynamics(DynamicDetailActivity.this, dynamicsDetail.getId(), FollowModel.DYNAMIC_TYPE);
                }
            }
        });

        mIvDynamicsUserHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(mUid) && mUid.equals(Constants.uid)) {
                    finish();
                } else {
                    Intent intent = new Intent(DynamicDetailActivity.this, HomePageActivity.class);
                    intent.putExtra("id", dynamicsDetail.getUid() + "");
                    startActivity(intent);
                }
            }
        });

        mTvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final BaseDialog dialog = new BaseDialog(DynamicDetailActivity.this, R.layout.dialog_private, Gravity.CENTER, true);
                ((TextView) dialog.getView(R.id.tv_dialog_content)).setText("确定删除该动态?");
                ((TextView) dialog.getView(R.id.tv_dialog_title)).setText("提示");
                ((TextView) dialog.getView(R.id.btn_confirm)).setText("确定");
                dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.toggleDialog();
                    }
                });
                dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPresenter.deleteDynamics(DynamicDetailActivity.this, mDynamicsID);
                        dialog.toggleDialog();
                    }
                });
                dialog.toggleDialog();
            }
        });

        mTvDynamicTopic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(mCid)) {
                    Intent intent = new Intent(DynamicDetailActivity.this, TopicDetailActivity.class);
                    intent.putExtra("id", mCid);
                    startActivity(intent);
                } else {
                    finish();
                }
            }
        });
    }

    private boolean sendComment() {
        //这里写发送信息的方法
        String messge = mEtCommentInput.getText().toString();

        if (TextUtils.isEmpty(messge)) {
            ToastUtils.showToast("评论消息不能为空");
            return true;
        }

//                    String encodeMsg = null;
//                    try {
//                        encodeMsg = URLEncoder.encode(messge,"UTF-8");
//                    } catch (UnsupportedEncodingException e) {
//                        e.printStackTrace();
//                        encodeMsg = messge;
//                    }
        if (mCurReply != null) {
//                        mPresenter.commentDynamics(DynamicDetailActivity.this,
//                                String.valueOf(mDynamicsID), String.valueOf(mCurReply.getId())
//                                , String.valueOf(mCurReply.getUid()), encodeMsg);
            mPresenter.commentDynamics(DynamicDetailActivity.this,
                    1, String.valueOf(mDynamicsID), String.valueOf(mCurReply.getId())
                    , String.valueOf(mCurReply.getUid()), EmojiUtils.escape(messge));
        } else {
//                        mPresenter.commentDynamics(DynamicDetailActivity.this,
//                                String.valueOf(mDynamicsID), null, null, encodeMsg);
            mPresenter.commentDynamics(DynamicDetailActivity.this,
                    0, String.valueOf(mDynamicsID), null, null, EmojiUtils.escape(messge));
        }

        hideReplyUser();
        clearEditText();
        return false;
    }

    private void clearEditText() {
        mEtCommentInput.setText("");
//        mEtComment.setText("");
    }

    private void hideReplyUser() {
        mCurReply = null;
        mHostName = null;
        mEtCommentInput.setHint("说点什么吧");
//        mEtComment.setHint("说点什么吧");
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setEnableLoadmore(false);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.queryDynamicsDetail(DynamicDetailActivity.this, mDynamicsID);
            }
        });
    }

    private void initData() {
        manager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
        rightImage.setVisibility(View.GONE);
        mDynamicsID = getIntent().getIntExtra(DYNAMICS_ID, 0);
        mUid = getIntent().getStringExtra(DYNAMICS_UID);
        mCid = getIntent().getStringExtra(DYNAMICS_CID);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        Date curDate = cal.getTime();
        curTime = curDate.getTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mKeyboardChangeListener != null) {
            mKeyboardChangeListener.destroy();
            mKeyboardChangeListener = null;
        }
        if (unbinder != null) {
            unbinder.unbind();
            unbinder = null;
        }
    }

    private void initKeyBoardListener() {
        mKeyboardChangeListener = new KeyboardChangeListener(this);
        mKeyboardChangeListener.setKeyBoardListener(this);
    }

    private void initView() {
//        mFriendsCircleImageLayout.setImageUrls(Arrays.asList(mImages3));

//        commentAdapter = new DynamicCommentAdapter(getTestCourseList2());
//        commentAdapter = new DynamicCommentAdapter(new ArrayList<>());
//        mEtComment.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
//        mEtComment.setSingleLine(false);
//        mEtCommentInput.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
//        mEtCommentInput.setSingleLine(false);

        commentReplyAdapter = new ReplyListAdapter(new ArrayList<>());
        mRvFriendComments.setLayoutManager(new LinearLayoutManager(this));
        mRvFriendComments.setAdapter(commentReplyAdapter);
        mRvFriendComments.setNestedScrollingEnabled(false);
        if (!TextUtils.isEmpty(Constants.uid)) {
            if (Constants.uid.equals(mUid)) {
                mTvDelete.setVisibility(View.VISIBLE);
            } else {
                mTvDelete.setVisibility(View.GONE);
            }
        } else {
            mTvDelete.setVisibility(View.GONE);
        }
    }

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        if (isShow) {
            mLlSendComment.setVisibility(View.VISIBLE);
            mEtCommentInput.requestFocus();
//            mRlDynamicsComment.setVisibility(View.GONE);
        } else {
            mLlSendComment.setVisibility(View.GONE);
//            mRlDynamicsComment.setVisibility(View.VISIBLE);
//            mEtComment.requestFocus();
            hideReplyUser();
//            String msg = mEtCommentInput.getText().toString();
//            mEtComment.setText(msg);
//            mEtComment.setSelection(msg.length());
        }
    }

    @Override
    public void getFiendDynamicsDetail(DynamicsDetailBean result) {
        isZan = result.getIsCollection();
        if (0 == result.getIsCollection()) {
            mIvFriendDynamicsLike.setImageResource(R.mipmap.dynamic_no_like);
        } else {
            mIvFriendDynamicsLike.setImageResource(R.mipmap.dynamic_like);
        }
        DynamicsDetailBean.DynamicsDetail map = result.getMap();
        if (map != null) {
            dynamicsDetail = map;
            zanNum = dynamicsDetail.getZanNum();
            if (TextUtils.isEmpty(map.getUseravatar())) {
                GlideUtils.loadImg(this, mIvDynamicsUserHead, R.mipmap.default_user_head);
            } else {
                GlideUtils.loadBackImg(this, mIvDynamicsUserHead, map.getUseravatar(), R.mipmap.default_user_head);
            }
            mTvDynamicsUserName.setText(map.getNickname());
            Date itemDate = null;
            try {
                itemDate = CalendarUtils.string2Date(map.getCreated());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (itemDate != null) {
                mTvDynamicsTime.setText(CalendarUtils.getFriendlytime(itemDate));
            } else {
                mTvDynamicsTime.setText("刚刚");
            }
            mTvDynamicsContent.setText(Utils.getDecodeStr(map.getContent()));
            if (!TextUtils.isEmpty(map.getTitle())) {
                mTvDynamicTopic.setVisibility(View.VISIBLE);
                mTvDynamicTopic.setText("#" + map.getTitle() + "#");
            }
            if (!TextUtils.isEmpty(map.getReAddress())) {
                mTvAddress.setText(map.getReAddress());
            }
            if (!TextUtils.isEmpty(map.getImg())) {
                final String[] mImages = map.getImg().split(",");
                mFriendsCircleImageLayout.setImageUrls(Arrays.asList(mImages), new FriendsCircleImageLayout.onImageListener() {
                    @Override
                    public void onClick(int pos) {
                        PhotoScanActivity.startPhotoScan(DynamicDetailActivity.this, Arrays.asList(mImages), pos);
                    }
                });
            }
            mTvFriendDynamicsLikenum.setText(map.getZanNum() + "");
//            String format = getResources().getString(R.string.dynamic_detail_commentnum);
//            String comnum = String.format(format, map.getComNum());//对应xml中定义的123顺序
            mTvCommentNum.setText(map.getComNum() + "");
        }

        List<ReplyBean> list = result.getComList();
        if (list != null && list.size() > 0) {
            mRlFriendComments.setVisibility(View.VISIBLE);
            commentReplyAdapter.setNewData(list);
        } else {
            mRlFriendComments.setVisibility(View.GONE);
        }

        mRefreshLayout.finishRefresh();
    }

    @Override
    public void commentDynamicsSuccess(JSONObject result) {
        ToastUtils.showToast("发送评论成功");
        mPresenter.queryDynamicsDetail(DynamicDetailActivity.this, mDynamicsID);
        EventBus.getDefault().post(new EventBean(Constants.EventCode.REPLY_DYNAMICS, null));
    }

    @Override
    public void followDynamicsSuccess(JSONObject jsonObject) {
        if (0 == isZan) {
            isZan = 1;
            zanNum = zanNum + 1;
            mIvFriendDynamicsLike.setImageResource(R.mipmap.dynamic_like);
            mTvFriendDynamicsLikenum.setText(String.valueOf(zanNum));
        } else {
            isZan = 0;
            zanNum = zanNum - 1;
            mIvFriendDynamicsLike.setImageResource(R.mipmap.dynamic_no_like);
            mTvFriendDynamicsLikenum.setText(String.valueOf(zanNum));
        }
        EventBus.getDefault().post(new EventBean(Constants.EventCode.LIKE_DYNAMICS, null));
    }

    @Override
    public void deleteDynamicsSuccess(JSONObject jsonObject) {
        EventBus.getDefault().post(new EventBean(Constants.EventCode.DELETE_DYNAMICS, null));
        finish();
    }
}
